<template>
  <div>
    <!-- <div class="treeBox">
      进货量/库存: <span class="red">51260/318</span> , 预估利润: <span class="red">--</span> , 压资: <span class="red">30324</span>
    </div> -->
    <!--引用表格-->
    <BasicTable
      @register="registerTable"
      :rowSelection="rowSelection"
      :isAcrossPage="false"
      :rowClassName="(record, index) => (record.isRed || record.isRed == 1 ? 'pink' : record.useState == 4 ? 'grey' : null)"
    >
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button @click="handleTips(1)" color="warning"> 标记优先</a-button>
        <a-button @click="handleTips(2)"> 取消标记</a-button>
        <!-- <a-button type="primary" @click="copyCode"> 一键复制券码</a-button> -->
        <a-button type="primary" @click="copyID"> 一键复制ID</a-button>
        <a-button @click="batchHandleDelete" color="error"> 删除优惠券</a-button>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
      <!--字段回显插槽-->
      <template v-slot:bodyCell="{ column, record, index, text }"> </template>
      <!-- 测试列数据 -->
      <template #isShow="{ record }">
        <Image v-if="true" :src="record.couponCode" :width="80" :height="100" />
        <div style="color: blue">{{ record.code }}</div>
      </template>

      <!-- 原因 -->

      <template #reason="{ record }">
        <div style="white-space: pre-line" v-html="record.reason"></div>
      </template>
      <!-- id -->
      <template #ID="{ record }">
        <div :style="record.isPriority ? 'color: rgb(230, 162, 60)' : ''">{{ record.id }}</div>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <CardModal @register="registerModal" @success="handleSuccess"></CardModal>
    <!-- 删除弹窗 -->

    <a-modal v-model:visible="visible" title="是否删除数据" @ok="handleOk">
      <a-form ref="formRef" layout="horizontal" size="middle" :model="formState">
        <a-form-item label="删除原因" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }" name="delReason" :rules="[{ required: true, message: '请填写删除原因' }]">
          <a-input v-model:value="formState.delReason" placeholder="请输入删除原因" />
        </a-form-item>
        <a-form-item label="操作人" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }" name="delOperator" :rules="[{ required: true, message: '请填写操作人' }]">
          <a-input v-model:value="formState.delOperator" placeholder="请输入操作人" />
        </a-form-item>
        <a-form-item label="操作密码" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }" name="delPassword" :rules="[{ required: true, message: '请填写操作密码' }]">
          <a-input v-model:value="formState.delPassword" placeholder="请输入操作密码" />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model:visible="visible1" title="是否删除数据" @ok="handleOk1">
      <a-form ref="formRef1" layout="horizontal" size="middle" :model="formState">
        <a-form-item label="删除原因" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }" name="delReason" :rules="[{ required: true, message: '请填写删除原因' }]">
          <a-input v-model:value="formState.delReason" placeholder="请输入删除原因" />
        </a-form-item>
        <a-form-item label="操作人" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }" name="delOperator" :rules="[{ required: true, message: '请填写操作人' }]">
          <a-input v-model:value="formState.delOperator" placeholder="请输入操作人" />
        </a-form-item>
        <a-form-item label="操作密码" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }" name="delPassword" :rules="[{ required: true, message: '请填写操作密码' }]">
          <a-input v-model:value="formState.delPassword" placeholder="请输入操作密码" />
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 备注 -->
    <a-modal v-model:visible="remakeIsShow" title="备注" @ok="remakeOk">
      <div style="display: flex; align-items: center; padding: 16px; box-sizing: border-box">
        <div style="width: 100px"> 备注 </div> <a-input v-model:value="remark" placeholder="请输入备注" />
      </div>
    </a-modal>
    <canvas id="canvas" style="display: none"></canvas>
    <image id="imageToCopy" style="display: none"></image>
  </div>
</template>

<script lang="ts" name="card-card" setup>
  import { reactive, ref } from 'vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { Image } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import CardModal from './components/CardModal.vue';
  import { columns, searchFormSchema, superQuerySchema } from './Card.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl, tipsChange, editRemake } from './Card.api';
  import { useRoute } from 'vue-router';
  import { useForm, BasicForm, FormSchema } from '/@/components/Form';
  const route = useRoute();
  const queryParam = reactive<any>({});
  const { createMessage } = useMessage();
  const visible = ref(false);
  const visible1 = ref(false);
  const id = ref('');
  const remakeIsShow = ref(false);
  const formState = reactive({
    delReason: '',
    delOperator: '',
    delPassword: '',
  });
  const remark = ref('');
  
  // 创建表单引用
  const formRef = ref();
  const formRef1 = ref();
  const formSchemas: FormSchema[] = [
    {
      //标题名称
      label: '删除原因',
      //字段
      field: 'delReason',
      //组件 支持组件详见 components/Form/src/types/index.ts 中的 ComponentType
      component: 'Input',
      //标题宽度,支持数字和字符串
      labelWidth: 100,
      //标题长度，超过位数隐藏
      labelLength: 4,
      //一列占比总共24，比如一行显示2列
      colProps: { span: 24 },
    },
    {
      //标题名称
      label: '操作人',
      //字段
      field: 'delOperator',
      //组件 支持组件详见 components/Form/src/types/index.ts 中的 ComponentType
      component: 'Input',
      //标题宽度,支持数字和字符串
      labelWidth: 100,
      //标题长度，超过位数隐藏
      labelLength: 4,
      //一列占比总共24，比如一行显示2列
      colProps: { span: 24 },
    },
  ];
  const [registerForm, { setProps }] = useForm({
    schemas: formSchemas,
    //显示操作按钮
    showActionButtonGroup: false,
  });
  //注册model
  const [registerModal, { openModal }] = useModal();
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '卡券',
      api: list,
      columns,
      canResize: false,
      clearSelectOnPageChange: true,
      formConfig: {
        //labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [['createTime', ['startTime', 'endTime'], 'YYYY-MM-DD']],
      },
      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        params.cardTypeId = route.query.id;
        console.log('params', params);
        setSelectedRowKeys([]);
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: '卡券',
      url: getExportUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });

  const [registerTable, { reload, setSelectedRowKeys }, { rowSelection, selectedRowKeys, selectedRows }] = tableContext;

  // 一键复制ID
  function copyID() {
    try {
      let str = selectedRowKeys.value.join(); // 默认以逗号分隔
      if (str == '') {
        createMessage.error('复制失败,未选中数据');
        return;
      }
      if (navigator.clipboard) {
        navigator.clipboard.writeText(str);
        createMessage.success('复制成功');
      } else {
        const textarea = document.createElement('textarea');
        textarea.value = str;
        textarea.style.position = 'fixed';
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        createMessage.success('复制成功');
      }
    } catch (error) {
      // console.log(error);
      createMessage.error('复制失败');
    }
  }
  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }
  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: false,
    });
  }

  // 添加备注

  async function remakeOk() {
    if (remark.value == '') {
      createMessage.error('请填写备注');
      return;
    }
    await editRemake({ id: id.value, remark: remark.value }, handleSuccess);
    remark.value = '';
    remakeIsShow.value = false;
  }

  /**
   * 确认删除
   */
  async function handleOk() {
    try {
      // 使用组件验证表单
      await formRef.value.validate();
      
      // 验证通过后执行删除操作
      await deleteOne({ id: id.value, delReason: formState.delReason, delOperator: formState.delOperator, delPassword: formState.delPassword }, handleSuccess);
      formState.delReason = '';
      formState.delOperator = '';
      formState.delPassword = '';
      visible.value = false;
    } catch (error) {
      // 验证失败时会自动显示错误提示，无需额外处理
      console.log('表单验证失败', error);
    }
  }
  /**
   * 批量确认删除
   */
  async function handleOk1() {
    try {
      // 使用组件验证表单
      await formRef1.value.validate();
      
      // 验证通过后执行批量删除操作
      await batchDelete({ ids: selectedRowKeys.value, delReason: formState.delReason, delOperator: formState.delOperator, delPassword: formState.delPassword }, handleSuccess);
      formState.delReason = '';
      formState.delOperator = '';
      formState.delPassword = '';
      visible1.value = false;
    } catch (error) {
      // 验证失败时会自动显示错误提示，无需额外处理
      console.log('表单验证失败', error);
    }
  }
  /**
   * 删除事件
   */
  function handleDelete(record) {
    id.value = record.id;
    formState.delReason = '';
    formState.delOperator = '';
    formState.delPassword = '';
    visible.value = true;
    console.log('visible', visible);
  }

  function handleRemake(record) {
    id.value = record.id;
    remark.value = '';
    remakeIsShow.value = true;
  }

  // 添加标记或取消标记
  async function handleTips(type) {
    await tipsChange({ ids: selectedRowKeys.value, isPriority: type }, handleSuccess);
  }

  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    formState.delReason = '';
    formState.delOperator = '';
    visible1.value = true;
  }
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      // {
      //   label: '编辑',
      //   onClick: handleEdit.bind(null, record),
      // },
      {
        label: '删除',
        onClick: handleDelete.bind(null, record),
      },
      {
        label: '备注',
        onClick: handleRemake.bind(null, record),
      },
    ];
  }
</script>

<style lang="less" scoped>
  :deep(.ant-picker),
  :deep(.ant-input-number) {
    width: 100%;
  }
  .treeBox {
    margin: 10px;
    background: #fff;
    padding: 20px;
    box-sizing: border-box;
    .red {
      color: red;
    }
  }
  ::v-deep .jeecg-basic-table .ant-table-tbody tr {
    background-color: #fff; // 自定义悬停背景色
  }

  ::v-deep .jeecg-basic-table .ant-table-tbody tr > td {
    background-color: #fff; // 自定义悬停背景色
  }
  ::v-deep .jeecg-basic-table .ant-table-tbody .pink {
    background-color: pink !important; // 自定义悬停背景色
  }
  ::v-deep .jeecg-basic-table .ant-table-tbody .pink > td {
    background-color: pink !important; // 自定义悬停背景色
  }
  ::v-deep .jeecg-basic-table .ant-table-tbody .grey {
    background-color: grey !important; // 自定义悬停背景色
  }
  ::v-deep .jeecg-basic-table .ant-table-tbody .grey > td {
    background-color: grey !important; // 自定义悬停背景色
  }

  ::v-deep .jeecg-basic-table .ant-table-tbody tr:hover > td {
    background-color: #f5f7fa !important; // 自定义悬停背景色
  }
</style>
